// //  进度条引入设置如上面第一种描述一样
import router from './router'
import store from './store'
import NProgress from 'nprogress' // progress bar
import 'nprogress/nprogress.css' // progress bar style
// import { getToken } from '@/utils/auth' // get token from cookie
import { validatenull } from '@/util/validate'

import { getAsyncRoutes } from '@/router/asyncRouter'
import { initDynamicRoutes } from "@/router"
const whiteList = ['/login'];
router.beforeEach( async (to, from, next) => {
    NProgress.start()
    if(to.meta.title){
        document.title = to.meta.title;
    }
    // 获取用户token，用来判断当前用户是否登录
    const hasToken = store.getters.access_token
    if (hasToken) {
        if (to.path === '/login') {
            next({ path: '/' })
            NProgress.done()
        } else {
            const value = to.query.src || to.fullPath
            const label = to.query.name || to.name
            const parentId = to.query.parentId
            if(!validatenull(value) && !validatenull(label)){
                store.commit('ADD_TAG', {
                    label: label,
                    value: value,
                    params: to.params,
                    query: to.query,
                    group: [],
                    parentId: parentId
                })
            }


            // initDynamicRoutes()
            //异步获取store中的路由
            next()
            // console.log(s);
            // const hasRoutes = store.getters.addRoutes;
            // if(hasRoutes){
            //     next()
            // }else{
            //     const accessRoutes = await store.dispatch('getRole', {role:'admin'})
            //     router.addRoutes(getAsyncRoutes(accessRoutes))
            //     next({ ...to, replace: true })
            // }
        }
    } else {
        if (whiteList.indexOf(to.path) !== -1) {
            next()
        } else {
            next(`/login`)
            NProgress.done()
        }
    }
})
 
router.afterEach(() => {
    NProgress.done()
})

